package com.sf.fy.uav.applet.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sf.fy.uav.applet.config.DelayQueue;
import com.sf.fy.uav.applet.order.service.OrderService;
import com.sf.fy.uav.applet.user.service.AboutUserService;
import com.sf.fy.uav.common.awt.RepeatSubmit;
import com.sf.fy.uav.common.enums.OrderStatusEnum;
import com.sf.fy.uav.common.request.order.*;
import com.sf.fy.uav.common.response.order.CarrierWaybillResponse;
import com.sf.fy.uav.common.response.order.FeeDetailsResponse;
import com.sf.fy.uav.common.response.order.OrderResponse;
import com.sf.fy.uav.common.response.order.PlaceOrderResponse;
import com.sf.fy.uav.common.response.user.UserResponse;
import com.sf.fy.uav.common.utils.BeanUtil;
import com.sf.fy.uav.common.utils.Rs;
import com.sf.fy.uav.entity.ErrandOrder;
import com.sf.fy.uav.order.controller.ErrandOrderRest;
import com.sf.fy.uav.order.controller.FeedbackRest;
import com.sf.fy.uav.order.controller.FeedbackTypeRest;
import com.sf.fy.uav.order.controller.OrderInfoRest;
import com.sf.fy.uav.order.entity.OrderInfo;
import com.sf.fy.uav.order.mapper.OrderInfoMapper;
import com.sf.fy.uav.order.service.IOrderInfoService;
import com.sf.fy.uav.rest.SysTcRest;
import com.sf.fy.uav.user.entity.User;
import com.sf.fy.uav.user.rest.UserRest;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.sf.fy.uav.common.enums.ServicePrefixEnum;
import com.sf.fy.uav.common.utils.RedisPrefixKey;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author LTQ
 */
@RestController
@RequestMapping("/sys/order/")
public class OrderController {
    @Autowired
    private IOrderInfoService iOrderInfoService;

    @Autowired
    private DelayQueue delayQueue;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    private ErrandOrderRest errandOrderRest;

    private SysTcRest sysTcRest;

    @Value("${encrypt.config-env:test}")
    private String encryptConfigEnv;


    @Value("${count.down.door_to_door_pickup:18}")
    private Integer countDownDoorToDoorPickUp;


    @Value("${count.down.drone_has_been_picked_up:5}")
    private Integer countDroneHasBeenPickedUp;

    @Value("${count.down.drone_delivery_in_progress:40}")
    private Integer countDroneDeliveryInProgress;

    @Value("${count.down.to_be_dispatched:30}")
    private Integer countDownToBeDispatched;

    private final static Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private UserRest userRest;

    @Autowired
    private OrderService orderService;


    @Autowired
    private OrderInfoRest orderInfoRest;

    @Autowired
    private AboutUserService aboutUserService;

    @Autowired
    private FeedbackTypeRest feedbackTypeRest;

    @Autowired
    private FeedbackRest feedbackRest;

    public OrderController() {
    }

    @GetMapping("get-user-info")
    public Rs<UserResponse> getByUserId() {
        return Rs.success(userRest.getByUserId());
    }

    /**
     * 匹配站点
     *
     * @return
     */
    @PostMapping("matching-sites")
    @Operation(tags = "查询是否可以下单", description = "询单")
    public Rs<CarrierWaybillResponse> matchingSites(@RequestBody @Validated PreCarrierWaybillRequest preCarrierWaybillRequest) {
        return Rs.success(iOrderInfoService.matchingSites(preCarrierWaybillRequest));
    }


    /**
     * 获取费用明细
     *
     * @return
     */
    @GetMapping("get-fee-details")
    @Operation(tags = "获取费用明细", description = "获取费用明细")
    public Rs<FeeDetailsResponse> getFeeDetails(@RequestParam String orderId) {
        return Rs.success(orderService.getFeeDetails(orderId));
    }

    /**
     * 下单接口
     *
     * @return
     */
    @PostMapping("place-order")
    @RepeatSubmit(interval = 1000, message = "重复提交")
    @Operation(tags = "下单", description = "下单")
    public Rs<PlaceOrderResponse> placeOrder(@Valid @RequestBody PrepareOrderRequest prepareOrderRequest) {
        prepareOrderRequest.setWebType(0);
        return Rs.success(orderService.placeOrder(prepareOrderRequest));
    }


    @PostMapping("place-order-for-h5")
    @RepeatSubmit(interval = 1000, message = "重复提交")
    @Operation(tags = "h5下单", description = "h5下单")
    public Rs<PlaceOrderResponse> placeOrderForH5(@Valid @RequestBody PrepareOrderForH5Request prepareOrderForH5Request) {
        PrepareOrderRequest prepareOrderRequest = BeanUtil.copyProperties(prepareOrderForH5Request, PrepareOrderRequest.class);
        prepareOrderRequest.setWebType(1);
        return Rs.success(orderService.placeOrder(prepareOrderRequest));
    }

    /**
     * 查询订单
     *
     * @return
     */
    @PostMapping("select-order")
    public Rs<JSONObject> selectOrder(@RequestBody SelectOrderRequest selectOrderRequest) {
        return Rs.success(orderService.selectOrder(selectOrderRequest));
    }

    @GetMapping("get-send-orders")
    public Rs<List<OrderResponse>> getSendOrder(@RequestParam Integer page, @RequestParam Integer size) {
        return Rs.success(orderInfoRest.getSendOrder(page, size));
    }


    @GetMapping("get-send-orders-total")
    public Rs<Long> getSendOrderTotal() {
        return Rs.success(orderInfoRest.getSendOrderTotal());
    }

    @GetMapping("get-receive-orders")
    public Rs<List<OrderResponse>> getReceiveOrder(@RequestParam Integer page, @RequestParam Integer size) {
        User user = userRest.getUser();
        return Rs.success(orderInfoRest.getReceiveOrder(user.getPhoneNumber(), page, size));
    }

    @GetMapping("get-receive-orders-total")
    public Rs<Long> getReceiveOrderTotal() {
        User user = userRest.getUser();
        return Rs.success(orderInfoRest.getReceiveOrderTotal(user.getPhoneNumber()));
    }


    @PostMapping("update-status")
    @Operation(tags = "更新订单状态接口", description = "更新订单状态接口")
    public Rs<Void> updateStatus(@Valid @RequestBody UpdateOrderInfoStatusRequest updateOrderInfoStatusRequest) {
        logger.info("updateOrderInfoStatusRequest:{}" + updateOrderInfoStatusRequest.toString());
        Boolean b = iOrderInfoService.updateExpressOrderStatus(updateOrderInfoStatusRequest);
        String tcWaybillNo = updateOrderInfoStatusRequest.getTcWaybillNo();
        Integer orderStatus = updateOrderInfoStatusRequest.getOrderStatus();
        QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
        orderInfoQueryWrapper.eq("tc_waybill_no", tcWaybillNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(orderInfoQueryWrapper);
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        String errandOrderSn = updateOrderInfoStatusRequest.getErrandOrderSn();
        if (!ObjectUtils.isEmpty(orderInfo) && b) {
            String key = ServicePrefixEnum.SAME_CITY.toString();
            if (orderStatus.equals(OrderStatusEnum.DOOR_TO_DOOR_PICKUP.getStatus())) {
                key += RedisPrefixKey.DOOR_TO_DOOR_PICKUP_DOWN;
                c.add(Calendar.MINUTE, countDownDoorToDoorPickUp);
                if (!ObjectUtils.isEmpty(errandOrderSn)) {
                    //需要触发定时获取骑手坐标
                    delayQueue.pushQueue(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.UPDATE_RIDER_COORDINATES + errandOrderSn, 0L);
                }
            } else if (orderStatus.equals(OrderStatusEnum.DRONE_HAS_BEEN_PICKED_UP.getStatus())) {
                key += RedisPrefixKey.DRONE_HAS_BEEN_PICKED_UP_DOWN;
                c.add(Calendar.MINUTE, countDroneHasBeenPickedUp);
            } else if (orderStatus.equals(OrderStatusEnum.DRONE_DELIVERY_IN_PROGRESS.getStatus())) {
                key += RedisPrefixKey.DRONE_DELIVERY_IN_PROGRESS_DOWN;
                c.add(Calendar.MINUTE, countDroneDeliveryInProgress);
            } else if (orderStatus.equals(OrderStatusEnum.TO_BE_DISPATCHED.getStatus())) {
                key += RedisPrefixKey.TO_BE_DISPATCHED_DOWN;
                c.add(Calendar.MINUTE, countDownToBeDispatched);
                if (!ObjectUtils.isEmpty(errandOrderSn)) {
                    //需要触发定时获取骑手坐标
                    delayQueue.pushQueue(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.UPDATE_RIDER_COORDINATES + errandOrderSn, 0L);
                }
            }
            delayQueue.pushQueue(key + orderInfo.getId(), c.getTime().getTime() - date.getTime());
        }
        return Rs.success();
    }


}
